package com.frxuexi.myroom.paging

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.frxuexi.lib_base.room.Leave
import com.frxuexi.myroom.repository.LeaveRepo
import java.lang.Exception

class MyDataSource(leaveRepo: LeaveRepo,uid:Int):PagingSource<Int,Leave>() {
    var leaveRepo=leaveRepo
    var uid=uid
    override fun getRefreshKey(state: PagingState<Int, Leave>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Leave> {
        return try {
            var currentPage=params.key?:1

            val list = leaveRepo.selectLeavesByUid(uid, currentPage, 10)

            val count = leaveRepo.getCount(uid)
            var sum = if(count/10==0) count/10 else count/10+1
            var nextPage=if(currentPage<sum){
                currentPage+1
            }else{
                null
            }

            LoadResult.Page(list,null,nextPage)
        }catch (e:Exception){
            LoadResult.Error(e)
        }
    }
}